//
//  UIImageView+Extentions.swift
//  TeaShop
//
//  Created by 刘泽 on 2018/1/14.
//  Copyright © 2018年 刘泽. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

extension UIImageView{

    /// 要在添加到superView上之后才可以调用
    /// 并layout结束调用才有效果
    /// - Parameters:
    ///   - shadowColor: 阴影颜色
    ///   - shadowOffSet: 阴影偏移
    ///   - shadowOpacity: 阴影透明度
    ///   - shadowRadius: 阴影宽度
    ///   - cornerRadius: 圆角
    func addShadowCorner(shadowColor:UIColor,shadowOffSet:CGSize,shadowOpacity:Float,shadowRadius:CGFloat,cornerRadius:CGFloat){

        layer.masksToBounds = true
        layer.cornerRadius = cornerRadius

        let cornerLayer = CALayer()
        cornerLayer.frame = frame
        cornerLayer.backgroundColor = UIColor.white.cgColor
        cornerLayer.shadowRadius = shadowRadius
        cornerLayer.shadowOpacity = shadowOpacity
        cornerLayer.shadowColor = UIColor.black.cgColor
        cornerLayer.shadowOffset = shadowOffSet
        cornerLayer.cornerRadius = cornerRadius

        superview?.layer.insertSublayer(cornerLayer, below: layer)

    }
    
    
   

    //MARK:获取视频缩略图
    public func getVideoImage(_ videoUrl:String){
        let dispatch = DispatchQueue(label: "videoImage")
        dispatch.async {
            let asset = AVURLAsset(url: URL(string: videoUrl)!)
            let gen = AVAssetImageGenerator(asset: asset)
            gen.appliesPreferredTrackTransform = true
            let time = CMTimeMake(0, 600)
            var actualTime : CMTime = CMTime(value: 0, timescale: 600)
            do{
                let image = try gen.copyCGImage(at: time, actualTime: &actualTime)
                DispatchQueue.main.async { [weak self] () in
                    self?.image = UIImage(cgImage: image)
                }

            }catch{
                print("获取缩略图失败")
            }
        }
    }

    //MARK:生成二维码
    public func creatQRcodeBy(_ string:String){
        let que1 = DispatchQueue(label: "qrcode")
        que1.async {[weak self] () in
            let filter = CIFilter(name: "CIQRCodeGenerator")
            filter?.setDefaults()
            let data = string.data(using: .utf8)
            filter?.setValue(data, forKey: "inputMessage")
            if let outputImage = filter?.outputImage{
                let qrcodeImage = self?.setupHighDefinitionUIImage(outputImage, size: 300)
                DispatchQueue.main.async {
                    self?.image = qrcodeImage
                }
            }

        }
    }

    //MARK:生成条形码
    public func creatBarCodeBy(_ string:String){
        let que1 = DispatchQueue(label: "barcode")
        que1.async {[weak self] () in
            let filter = CIFilter(name: "CICode128BarcodeGenerator")
            filter?.setDefaults()
            let data = string.data(using: .ascii)
            filter?.setValue(data, forKey: "inputMessage")
            filter?.setValue(0, forKey: "inputQuietSpace")
            if let outputImage = filter?.outputImage{
                let qrcodeImage = self?.setupHighDefinitionUIImage(outputImage, size: 300)
                DispatchQueue.main.async {
                    self?.image = qrcodeImage
                }
            }

        }
    }

    //MARK: - 生成高清的UIImage
    private func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)

        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!

        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!

        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }

}
